package com.mufeng.libs.net

import androidx.lifecycle.ViewModel
import androidx.lifecycle.rxLifeScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.onStart
import rxhttp.toDownloadFlow
import rxhttp.wrapper.param.*


fun <T> ViewModel.netRequest(block: RequestAction<T>.() -> Unit) {

    val action = RequestAction<T>().apply(block)

    rxLifeScope.launch {
        action.request?.invoke()
            ?.onStart {
                action.start?.invoke()
            }
            ?.catch {
                val msg = it.msg
                val code = it.code
                action.error?.invoke(code, msg)
            }?.collect {
                action.success?.invoke(it)
            }
    }

}

/**
 * 使用flow进行文件下载
 * @receiver RxHttp<*, *>
 * @param destPath String
 * @param onStart Function0<Unit>
 * @param onSuccess Function4<[@kotlin.ParameterName] String?, [@kotlin.ParameterName] Int, [@kotlin.ParameterName] Long, [@kotlin.ParameterName] Long, Unit>
 * @param onError Function2<[@kotlin.ParameterName] String, [@kotlin.ParameterName] String, Unit>
 */
suspend inline fun <reified T> RxHttp<*, *>.downFlow(
    destPath: String,
    crossinline onStart: () -> Unit,
    crossinline onProgress: (process: Int, currentSize: Long, totalSize: Long) -> Unit,
    crossinline onSuccess: (path: String?) -> Unit,
    crossinline onError: (code: String, msg: String) -> Unit
) {
    toDownloadFlow(destPath)
        .onProgress {
            val process = it.progress         //已下载进度  0-100
            val currentSize = it.currentSize  //已下载size，单位：byte
            val totalSize = it.totalSize      //要下载的总size  单位：byte
            onProgress(process, currentSize, totalSize)
        }
        .onStart {
            onStart()
        }
        .catch {
            val msg = it.msg
            val code = it.code
            onError(code, msg)
        }
        .collect {
            //此时这里将收到所有事件，这里的it为ProgressT<String>对象

            val path = it              //本地存储路径
            onSuccess(path)
        }
}
